obj = k2l.o
CFLAGS += -Wall -D_K2L_MAIN

ifeq ($(fast),y)
o3=y
gperf=y
stack=y
endif
ifeq ($(o3),y)
CFLAGS += -O3
endif
ifeq ($(gperf),y)
obj += k2l_gperf.o
CFLAGS += -D_K2L_USE_GPERF
endif
ifeq ($(stack),y)
CFLAGS += -D_K2L_USE_STACK
endif

.PHONY: all clean len

all: k2l

k2l: $(obj)
	$(CC) -o $@ $^ $(CFLAGS)

k2l.o: k2l.h k2l_symenum.h k2l_symtab.h 

%.o: %.c
	$(CC) -c $< $(CFLAGS)

k2l_gperf.c: k2l.gperf
	gperf -I -t k2l.gperf >$@

clean:
	rm -f k2l
	rm -f *.o
	rm -f k2l_gperf.c
	rm -f k2l_symenum.h k2l_symtab.h k2l.gperf

len:
	wc -l k2l.[ch]

K2L_AWK_PTN = !/^$$/

k2l_symenum.h: k2l_symtab.def
	awk -F ',' '$(K2L_AWK_PTN){gsub(" ", "", $$2); gsub("[+]", "a", $$2); gsub("[-]", "s", $$2); gsub("[*]", "m", $$2); gsub("[/]", "d", $$2); gsub("[%]", "p", $$2); gsub("[=]", "e", $$2); gsub("[>]", "g", $$2); gsub("[<]", "l", $$2); printf "K2L_SYM_%s, \n", $$2}' $^ >$@

k2l_symtab.h: k2l_symtab.def
	awk -F ',' '$(K2L_AWK_PTN){gsub(" ", "", $$2); gsub(" ", "", $$1); printf "DECLARE_%s(\"%s\",%s,%s), \n", $$1, $$2, $$3, $$4}' $^ >$@

K2L_AWK_BEGIN = i = 0; print "struct k2l_gperf{char *name; int idx;}\n%%"
K2L_AWK_END = print "%%\nint k2l_get_rsv_index(char* p) {struct k2l_gperf *g=in_word_set(p, strlen(p));return g? g->idx: -1;}"

k2l.gperf: k2l_symtab.def
	awk -F ',' 'BEGIN{$(K2L_AWK_BEGIN)} $(K2L_AWK_PTN){gsub(" ", "", $$2); printf "\"%s\", %d\n", $$2, i++} END{$(K2L_AWK_END)}' $^ >$@
